package com.huarun.module.visitorInvite.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.*;
import com.huarun.module.applyrecord.bean.ApplyRecord;
import com.huarun.module.applyrecord.service.IApplyRecordService;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.service.IUserService;
import com.huarun.module.visitorApply.service.VisitorApplyService;
import com.huarun.module.visitorInvite.bean.Visitor;
import com.huarun.module.visitorInvite.bean.VisitorApply;
import com.huarun.module.visitorInvite.service.VisitorInviteService;
import com.huarun.redis.RedisService;
import com.huarun.redis.RedisUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.alibaba.fastjson.JSON.toJSONString;

@Controller
@RequestMapping({"/wx/newVisitorInvite"})
public class VisitorInviteController extends BaseController {

    @Resource
    private IUserService userService;

    @Resource
    private VisitorInviteService visitorInviteService;

    @Resource
    private VisitorApplyService visitorApplyService;

    @Resource
    private IApplyRecordService applyRecordService;

    public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @ApiOperation(value = "根据openId邀约人信息", notes = "邀请访客")
    @RequestMapping(value = {"/invitedinfo"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Object> invitedinfo(HttpServletRequest request) {
        ResponseMessage rm = new ResponseMessage();
        Map userParam = new HashMap();
        String projectId = request.getHeader("projectId");
        userParam.put("openId", request.getHeader("openId"));

        User user = this.userService.getUserByParams(userParam);
        String wxPhone = user.getWxPhone();
        JSONObject jsonEmployee = new JSONObject();
        Map parames = new HashMap();
        if (projectId.equals(PropertyUtil.getProperty("chunsun_project_id"))) {
            String buildingName = "中国华润大厦";
            long time = System.currentTimeMillis();
            String sign_key = PropertyUtil.getProperty("sign_key");

            Map map = new HashMap();
            map.put("time", time);
            map.put("mobile", wxPhone);
            Gson gson = new Gson();
            String str = gson.toJson(map);
            str = new StringBuilder().append(str).append("&key=").append(sign_key).toString();
            String token = MD5Util.crypt(str).toUpperCase();

            jsonEmployee.put("sign", token);
            jsonEmployee.put("time", time);
            jsonEmployee.put("mobile", wxPhone);

            String url = PropertyUtil.getProperty("visitor_a_url") + PropertyUtil.getProperty("chunsun_employee_url");

            JSONObject employee = HttpRequestUtils.httpPost(url, jsonEmployee);

            System.out.println("==============春笋邀约返回:" + (employee == null ? "null" : employee.toJSONString()));
            if (employee != null) {
                JSONObject retdataJson = employee.getJSONObject("Retdata");
                String floor = retdataJson.getString("floor");
                retdataJson.replace("buildingName", buildingName);
                retdataJson.replace("complexFloor", floor);
                employee.put("isDegree", Integer.valueOf(0));
                rm.setData(employee);
            } else {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "未找到该手机号相关信息");
                return rm;
            }
        } else if ((projectId.equals(PropertyUtil.getProperty("huarun_d_project_id"))) ||
                (projectId.equals(PropertyUtil.getProperty("huarun_b_project_id"))) ||
                (projectId.equals(PropertyUtil.getProperty("huarun_c_project_id"))))
        {
            parames.put("mobile", wxPhone);
            parames.put("projectId", projectId);
            Map subject = this.visitorApplyService.getDepartment(parames);
            String userName = "";
            String telPhone = "";
            String department = "";
            if (subject != null) {
                department = (String)subject.get("department");
                userName = (String)subject.get("real_name");
                telPhone = (String)subject.get("phone");
            } else {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "未找到该手机号相关信息");
                return rm;
            }

            long time = new Date().getTime();

            String str = "/ThirdPart/api/v1/ProjectLessee/GetLesseeInfoByName/" + projectId + "/" +
                    URLUtil.encodeURIComponent(department) +
                    "appkey=" + PropertyUtil.getProperty("manage_appkey") + "&time=" + time +
                    PropertyUtil.getProperty("manage_secret");
            String token = MD5Util.getMD5Uppercase(str);

            String url = Constant.BASE_URL + "/ThirdPart/api/v1/ProjectLessee/GetLesseeInfoByName/" + projectId + "/" +
                    URLUtil.encodeURIComponent(department) +
                    "?appkey=" +
                    PropertyUtil.getProperty("manage_appkey") +
                    "&time=" + time + "&token=" + token;
            try
            {
                String doGet = HttpUtil.doGet(url);
                JSONArray jsonArray = JSONObject.parseObject(doGet).getJSONObject("Data").getJSONArray("LesseeInfo");
                JSONArray roomInfo = new JSONArray();
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jo = (JSONObject)JSON.toJSON(jsonArray.get(i));
                    roomInfo = jo.getJSONArray("RoomInfo");
                }
                String complexFloor = "";
                String buildingName = "";
                if (projectId.equals(PropertyUtil.getProperty("huarun_b_project_id")))
                    buildingName = "华润置地大厦B座";
                else if (projectId.equals(PropertyUtil.getProperty("huarun_c_project_id")))
                    buildingName = "华润置地大厦C座";
                else if (projectId.equals(PropertyUtil.getProperty("huarun_d_project_id"))) {
                    buildingName = "华润置地大厦D座";
                }
                if ((roomInfo != null) && (roomInfo.size() != 0)) {
                    for (int i = 0; i < roomInfo.size(); i++) {
                        JSONObject jo = (JSONObject)JSON.toJSON(roomInfo.get(i));
                        complexFloor = complexFloor + jo.getString("FloorName") + ",";
                    }
                }
                complexFloor = complexFloor.substring(0, complexFloor.length() - 1);
                String[] split = complexFloor.split(",");

                Set set = new HashSet();
                for (int i = 0; i < split.length; i++) {
                    set.add(split[i]);
                }
                String[] arrayResult = (String[])set.toArray(new String[set.size()]);

                StringBuilder floor = new StringBuilder();
                for (String string : arrayResult) {
                    floor.append(string).append(",");
                }
                floor = new StringBuilder(floor.length() > 0 ? floor.substring(0, floor.length() - 1) : "");
                String abc = "{\"errcode\":0,\"Retdata\":{\"flag\":\"1\",\"complexFloor\":\"1F,2F,3F\",\"buildingName\":\"建筑名称\",\"empName\":\"员工姓名\",\"tel\":\"13800138000\"},\"isDegree\":0,\"errmsg\":\"OK\"}";
                JSONObject parseObject = JSONObject.parseObject(abc);
                parseObject.getJSONObject("Retdata").replace("flag", Integer.valueOf(1));
                parseObject.getJSONObject("Retdata").replace("complexFloor", floor.toString());
                parseObject.getJSONObject("Retdata").replace("buildingName", buildingName);
                parseObject.getJSONObject("Retdata").replace("empName", userName);
                parseObject.getJSONObject("Retdata").replace("tel", telPhone);
                rm.setData(parseObject);
            } catch (Exception e) {
                e.printStackTrace();
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
                return rm;
            }
        }

        return rm;
    }

    @ApiOperation(value = "邀约人提交申请", notes = "邀请访客")
    @RequestMapping(value = {"/saveVisitorInvite"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage saveVisitorApply(HttpServletRequest request, @RequestBody JSONObject param, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer rows) {
        ResponseMessage rm = new ResponseMessage();
        String projectId = request.getHeader("projectId");
        Visitor visitor1 = JSON.parseObject(param.toJSONString(), Visitor.class);
        List<JSONObject> visitorList = JSON.parseArray(visitor1.getVisitorList().toString(), JSONObject.class);
        Map<String, Object> userParam = new HashMap();
        userParam.put("openId", request.getHeader("openId"));
        userParam.put("projectId", projectId);
        User user = this.userService.getUserByParams(userParam);
        Map<String, Object> map = new HashMap();
        Integer userId = user.getId();
        map.put("userId", userId);
        map.put("projectId", projectId);
//            page = Integer.valueOf(0);
//            rows = Integer.valueOf(0);
        PageInfo inviteMap = this.visitorInviteService.getMyInvited(map, page, rows);//得到的时间单位是秒
        List<Map<String, Object>> inviteMapList = inviteMap.getList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (JSONObject jsonObject : visitorList) {
            Visitor visitor = JSON.parseObject(toJSONString(jsonObject), Visitor.class);
            BeanUtil.copyProperties(visitor1, visitor);
            visitor.setVisitorNum(1);
            if (StringUtils.isBlank(visitor.getVisitorName())) {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "来访人名字不能为空");
                return rm;
            }
            String visitorMobile = visitor.getVisitorPhone();
            if (StringUtils.isBlank(visitorMobile)) {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "来访人手机号码不能为空");
                return rm;
            }
            if (visitor.getVisitorNum() == null) {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "随访人数不能为空");
                return rm;
            }
            if ((StringUtils.isBlank(visitor.getStartTime())) || (StringUtils.isBlank(visitor.getEndTime()))) {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "时间不能为空");
                return rm;
            }
            if (StringUtils.isBlank(visitor.getVisited())) {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "被访人姓名不能为空");
                return rm;
            }
            String visitedPhone = visitor.getVisitedPhone();
            if (StringUtils.isBlank(visitedPhone)) {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "被访人手机号码不能为空");
                return rm;
            }

            for (Map map2 : inviteMapList) {
                String status = (String) map2.get("status");
                if (!"已取消".equals(status)) {
                    String visitorPhone = (String)map2.get("visitorPhone");
                    Long startTimeStamp = Long.parseLong(map2.get("startTime").toString())*1000;
                    String start = DateUtils.timeStamp2Date(startTimeStamp+"", "yyyy-MM-dd HH:mm");
                    Long endTimeStamp = Long.parseLong(map2.get("endTime").toString())*1000;
                    String end = DateUtils.timeStamp2Date(endTimeStamp+"", "yyyy-MM-dd HH:mm");
                    boolean overlap = isOverlap(start, end, visitor.getStartTime(), visitor.getEndTime());
                    if (overlap && visitorMobile.equals(visitorPhone)) {
                        rm.setData("请勿提交重叠的访问时间");
                        rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "请勿提交重叠的访问时间");
                        return rm;
                    }
                }

            }
            boolean isSucceed = true;
            List list = new ArrayList();
            try {
                String chunsunProjectId = PropertyUtil.getProperty("chunsun_project_id");
                Map params = new HashMap();
                params.put("toComName", visitor.getCompanyName());
                params.put("toEmpName", visitor.getVisited());
                params.put("toEmpMobile", visitedPhone);
                // 提取楼层信息的数字
                String floor = "";
                String floorInfo = visitor1.getFloor();
                Pattern pattern = Pattern.compile("^(\\d+)");
                if(!StringUtils.isEmpty(floorInfo)){
                    Matcher matcher = pattern.matcher(floorInfo);
                    if(matcher.find()){
                        floor = matcher.group();
                    }
                }
                if(projectId.equals(chunsunProjectId)){
                    floor = !StringUtils.isEmpty(floor) ? floor : "1";
                }
                params.put("toFloor", floor);
                params.put("visitorName", visitor.getVisitorName());
                params.put("visitorPhone", visitorMobile);
                params.put("visitorCertNo", visitor.getVisitorCard());
                params.put("peopleCount", visitor.getVisitorNum());
                params.put("visitReason", visitor.getVisitedCasue());
                params.put("toDept", "");
                params.put("visitDate", visitor.getCreatetime());
                String chunsunHost = PropertyUtil.getProperty("visitor_a_url");
                String http;
                params.put("startTime", visitor.getStartTime());
                params.put("endTime", visitor.getEndTime());
                if (projectId.equals(chunsunProjectId)) {
                    long time = System.currentTimeMillis();
                    params.put("time", time);
                    // 签名
                    String signKey = PropertyUtil.getProperty("sign_key");// 约定密钥
                    String str = JSON.toJSONString(params);
                    str = str + "&key=" + signKey;
                    String md5Str = MD5Util.crypt(str).toUpperCase();
                    params.put("sign",md5Str);
                    this.log.info("========访客邀请：二维码入参====：" + JSONObject.toJSONString(params));
                    JSONObject returnJson = HttpRequestUtils.httpPost(chunsunHost+ "/api/Getqrcode", JSON.toJSONString(params));
                    http = returnJson != null ? returnJson.toJSONString() : "";
                }else {
                    this.log.info("========访客邀请：二维码入参====：" + JSONObject.toJSONString(params));
                    http = HttpRequestUtils.http(getBcdApiHost(projectId) + "/api/Getqrcode", params);
                }
                this.log.info("========访客邀请：二维码返回====：" + http);
                if ("0".equals(String.valueOf(JSONObject.parseObject(http).get("errcode")))) {
                    JSONObject retdata = JSONObject.parseObject(http).getJSONObject("Retdata");
                    if(projectId.equals(chunsunProjectId)){
                        String qrcodeNo = retdata.getString("qrcodeNo");
                        System.out.println("========访客邀请：春笋二维码标记====：" + qrcodeNo);
                        list.add(qrcodeNo);
                    }else {
                        String qrcode = retdata.getString("qrcodeAddress");
                        System.out.println("========访客邀请：BCD二维码地址====：" + qrcode);
                        list.add(URLUtil.replaceLanToWan(qrcode, getBcdApiHost(projectId)));
                    }
                }else {
                    isSucceed = false;
                }

                String otherVistorName = visitor.getOtherVistorName();
                if (otherVistorName != null) {
                    String[] strArray = otherVistorName.split("、");
                    for (int i = 0; i < strArray.length; i++) {
                        Map<String,Object> jsonCode = new HashMap();
                        jsonCode.put("toComName", visitor.getCompanyName());
                        jsonCode.put("toEmpName", visitor.getVisited());
                        jsonCode.put("toEmpMobile", visitedPhone);
                        jsonCode.put("toFloor", floor);
                        jsonCode.put("visitorName", strArray[i]);
                        jsonCode.put("visitorPhone", visitorMobile);
                        jsonCode.put("visitorCertNo", visitor.getVisitorCard());
                        jsonCode.put("peopleCount", visitor.getVisitorNum());
                        jsonCode.put("visitReason", visitor.getVisitedCasue());
                        jsonCode.put("toDept", "");
                        jsonCode.put("visitDate", visitor.getCreatetime());
                        String http2;
                        jsonCode.put("startTime", visitor.getStartTime());
                        jsonCode.put("endTime", visitor.getEndTime());
                        if (projectId.equals(chunsunProjectId)) {
                            long time = System.currentTimeMillis();
                            params.put("time", time);
                            // 签名
                            String signKey = PropertyUtil.getProperty("sign_key");// 约定密钥
                            String str = JSON.toJSONString(jsonCode) + "&key=" + signKey;
                            String md5Str2 = MD5Util.crypt(str).toUpperCase();
                            jsonCode.put("sign",md5Str2);
                            this.log.info("========访客邀请：二维码入参====：" + JSONObject.toJSONString(jsonCode));
                            JSONObject returnJson = HttpRequestUtils.httpPost(chunsunHost+ "/api/Getqrcode", JSON.toJSONString(jsonCode));
                            http2 = returnJson != null ? returnJson.toJSONString() : "";
                        }else {
                            this.log.info("========访客邀请：二维码入参====：" + JSONObject.toJSONString(jsonCode));
                            http2 = HttpRequestUtils.http(getBcdApiHost(projectId) + "/api/Getqrcode", jsonCode);
                        }
                        this.log.info("========访客邀请：二维码返回====：" + http2);
                        if ("0".equals(String.valueOf(JSONObject.parseObject(http2).get("errcode")))) {
                            JSONObject retdata = JSONObject.parseObject(http2).getJSONObject("Retdata");
                            if(projectId.equals(chunsunProjectId)){
                                String qrcodeNo = retdata.getString("qrcodeNo");
                                System.out.println("========访客邀请：春笋二维码标记====：" + qrcodeNo);
                                list.add(qrcodeNo);
                            }else {
                                String qrcode = retdata.getString("qrcodeAddress");
                                System.out.println("========访客邀请：BCD二维码地址====：" + qrcode);
                                list.add(URLUtil.replaceLanToWan(qrcode, getBcdApiHost(projectId)));
                            }
                        }else {
                            isSucceed = false;
                        }
                    }
                }
                if(!isSucceed){
                    rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
                    this.log.error("生成二维码失败,申请异常！");
                    return rm;
                }
                String symbol = Joiner.on(",").join(list);

                VisitorApply visitorApply = new VisitorApply();
                visitorApply.setVisitorName(visitor.getVisitorName());
                visitorApply.setVisitorPhone(visitorMobile);
                visitorApply.setVisitorNum(visitor.getVisitorNum());
                visitorApply.setStartTime(sdf.parse(visitor.getStartTime()));
                visitorApply.setEndTime(sdf.parse(visitor.getEndTime()));
                visitorApply.setVisited(visitor.getVisited());
                visitorApply.setVisitedPhone(visitedPhone);
                visitorApply.setVisitedCompanyPosition(visitor.getVisitedCompanyPosition());
                visitorApply.setVisitedCasue(visitor.getVisitedCasue());
                visitorApply.setFloor(floor);
                visitorApply.setOtherVistorName(visitor.getOtherVistorName());
                visitorApply.setApplytype(0);
                visitorApply.setCreateDate(new Date());
                visitorApply.setTwoDimension(symbol);

                this.visitorInviteService.save(visitorApply);
                ApplyRecord entity = new ApplyRecord();
                Integer applyId = visitorApply.getId();
                entity.setApplyId(applyId);
                entity.setUserId(user.getId());
                entity.setTitle("邀约访客申请");

                entity.setApplyType("邀约访客申请");
                entity.setInterviewee(visitor.getVisited());
                entity.setTypeCode(4);
                entity.setStatus("已提交");
                entity.setDescription(visitor.getVisitedCasue());
                entity.setCreateDate(new Date());
                entity.setProjectId(projectId);
                entity.setSynId(request.getHeader("synId"));
                entity.setSynMainId(request.getHeader("synMainId"));

                this.applyRecordService.save(entity);
                String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
                JSONObject codeOther = new JSONObject(new LinkedHashMap());
//                SmsContent content = new SmsContent(visitor.getVisitorName(), visitor.getVisitedCompanyPosition(), visitor.getStartTime(), visitor.getEndTime());
                JSONObject content = new JSONObject(new LinkedHashMap());
                content.put("guestName",visitor.getVisitorName());
                content.put("company",visitor.getVisitedCompanyPosition());
                content.put("dateFrom1",visitor.getStartTime());
                content.put("dateFrom2",visitor.getStartTime());
                content.put("dateEnd",visitor.getEndTime());
                content.put("VerificationCode",verifyCode);
                String hostAddress = PropertyUtil.getProperty("server_host_address");
                content.put("QRCodeLink",hostAddress+"/huarun/visitor.html?projectId="+projectId+"&applyId="+applyId);
                codeOther.put("businessCode", PropertyUtil.getProperty("visitor_sms_apply_busiCode"));
                codeOther.put("mobile", visitorMobile);
                codeOther.put("content", content);
                codeOther.put("secretKey", PropertyUtil.getProperty("visitor_sms_apply_secretKey"));
                codeOther.put("source", "华润小程序");
                codeOther.put("sourceNote", "华润小程序-邀请访客");
                this.log.info("========访客邀请：开始发送短信====");
                System.out.println(codeOther.toJSONString());
                JSONObject other = HttpRequestUtils.httpPost(PropertyUtil.getProperty("visitor_sms_url"), codeOther);
                this.log.info("========访客邀请：发送短信完成====");
                if(other != null && "SUCCESS".equals(other.get("sendStatus"))){
                    // 信息发送成功后存验证码到redis
                    Date endDate = DateUtils.parseDate(visitor.getEndTime(), DateUtils.DATE_FORMAT_DATETIME);
                    long cacheTime = ((endDate.getTime() - new Date().getTime()))/1000;
                    RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
                    redisUtils.set("invite_visitor_"+applyId,verifyCode,cacheTime);
                }
                rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
                rm.setData("申请提交成功！");
            } catch (Exception e) {
                rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
                this.log.error("申请异常！");
                e.printStackTrace();
            }
        }

        return rm;
    }

    @ApiOperation(value = "我邀请的详情", notes = "我邀请的详情")
    @RequestMapping(value = {"/getVisitorInviteDetail"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Map<String, Object>> getVisitorInviteDetail(HttpServletRequest req, @RequestBody Map<String, Object> map) {
        ResponseMessage rm = new ResponseMessage();
        try {
            Map inviteMap = this.visitorInviteService.getVisitorInviteId(map);

            Long endTime = (Long) inviteMap.get("endTime");
            Long startTime = (Long) inviteMap.get("startTime");
            long newTime = new Date().getTime() / 1000L;
            String status = (String) inviteMap.get("status");
            if (!status.equals("已取消")) {
                if (newTime < startTime.longValue())
                    inviteMap.put("statusCode", Integer.valueOf(5));
                else if (endTime.longValue() < newTime)
                    inviteMap.put("statusCode", Integer.valueOf(3));
                else
                    inviteMap.put("statusCode", Integer.valueOf(6));
            } else {
                inviteMap.put("statusCode", Integer.valueOf(4));
            }

            rm.setData(inviteMap);
            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("邀约申请详情异常！");
            e.printStackTrace();
        }
        return rm;
    }

    @ApiOperation(value = "预约列表详情", notes = "预约列表详情")
    @RequestMapping(value = {"/getVisitorInviteListDetail"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Map<String, Object>> getVisitorInviteListDetail(HttpServletRequest req, @RequestBody Map<String, Object> map) {
        ResponseMessage rm = new ResponseMessage();
        try {
            VisitorApply entity = new VisitorApply();
            entity.setId((Integer) map.get("applyId"));
            entity.setIsMaRead(Integer.valueOf(1));
            this.visitorInviteService.update(entity);

            Map inviteMap = this.visitorInviteService.getVisitorInviteId(map);
            Long endTime = (Long) inviteMap.get("endTime");
            long newTime = new Date().getTime() / 1000L;
            String status = (String) inviteMap.get("status");
            if (!status.equals("已取消")) {
                if (endTime.longValue() < newTime)
                    inviteMap.replace("statusCode", Integer.valueOf(3));
            } else {
                inviteMap.replace("statusCode", Integer.valueOf(4));
            }

            rm.setData(inviteMap);
            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("邀约申请详情异常！");
            e.printStackTrace();
        }
        return rm;
    }

    @ApiOperation(value = "我的邀请", notes = "我的邀请")
    @RequestMapping(value = {"/getMyInvited"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<PageInfo<Map<String, Object>>> getMyInvited(HttpServletRequest req, @RequestBody Map<String, Object> map) {
        ResponseMessage rm = new ResponseMessage();
        try {
            if (((String) map.get("btime") != "") && ((String) map.get("etime") != "")) {

                String btime = DateUtils.date2TimeStamp((String) map.get("btime"), "yyyy-MM-dd");
                String etime = DateUtils.date2TimeStamp((String) map.get("etime"), "yyyy-MM-dd");
                map.replace("btime", Long.valueOf(btime)/1000); //秒->毫秒
                map.replace("etime", Long.valueOf(etime)/1000+86400);
            }
            Map userParam = new HashMap();
            userParam.put("openId", req.getHeader("openId"));
            User user = this.userService.getUserByParams(userParam);
            Integer userId = user.getId();
            map.put("userId", userId);
            map.put("projectId", req.getHeader("projectId"));
            Integer page = (Integer) map.get("page");
            Integer rows = (Integer) map.get("rows");
            PageInfo inviteMap = this.visitorInviteService.getMyInvited(map, page, rows);

            rm.setData(inviteMap);
            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("我的邀请异常！");
            e.printStackTrace();
        }
        return rm;
    }

    @ApiOperation(value = "预约列表", notes = "预约列表")
    @RequestMapping(value = {"/getMyInvitedList"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<PageInfo<Map<String, Object>>> getMyInvitedList(HttpServletRequest req, @RequestBody Map<String, Object> map) {
        ResponseMessage rm = new ResponseMessage();
        try {
            if (((String) map.get("btime") != "") && ((String) map.get("etime") != "")) {
                String btime = DateUtils.date2TimeStamp((String) map.get("btime"), "yyyy-MM-dd");
                String etime = DateUtils.date2TimeStamp((String) map.get("etime"), "yyyy-MM-dd");
                map.replace("btime", Long.parseLong(btime)/1000);
                map.replace("etime", Long.parseLong(etime)/1000+86400);
            }
            Map userParam = new HashMap();
            userParam.put("openId", req.getHeader("openId"));
            User user = this.userService.getUserByParams(userParam);
            String wxPhone = user.getWxPhone();
            map.put("wxPhone", wxPhone);
            map.put("projectId", req.getHeader("projectId"));
            Integer page = (Integer) map.get("page");
            Integer rows = (Integer) map.get("rows");
            PageInfo inviteMap = this.visitorInviteService.getMyInvitedList(map, page, rows);
            rm.setData(inviteMap);
            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("预约列表异常！");
            e.printStackTrace();
        }
        return rm;
    }

    @ApiOperation(value = "取消邀约", notes = "取消邀约")
    @RequestMapping(value = {"/cancelInvited"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Object> cancelInvited(HttpServletRequest req, @RequestBody Map<String, Object> map) {
        ResponseMessage rm = new ResponseMessage();
        try {
            map.put("updateDate", new Date());
            map.put("status", "已取消");
            int flag = this.visitorInviteService.cancelInviteId(map);
            if (flag > 0) {
                VisitorApply entity = new VisitorApply();
                Date updateDate = (Date) map.get("updateDate");
                Integer id = (Integer) map.get("id");
                entity.setUpdateDate(updateDate);
                entity.setId(id);
                this.visitorInviteService.update(entity);
            }
            rm.setData("取消成功");
            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("邀约申请详情异常！");
            e.printStackTrace();
        }
        return rm;
    }

    @ApiOperation(value = "批准", notes = "批准")
    @RequestMapping(value = {"/approval"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Object> approval(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        ResponseMessage rm = new ResponseMessage();
        Integer applyId = (Integer) map.get("id");
        try {
            VisitorApply visitorApply = new VisitorApply();
            visitorApply.setId(applyId);
            visitorApply.setStatus("已审批");
            visitorApply.setStatuscode(2);
            visitorApply.setUpdateDate(new Date());
            String openId = req.getHeader("openId");
            visitorApply.setUpdateDate(new Date());
            Map param = new HashMap();
            param.put("openId", openId);
            param.put("applyId", applyId);

            User user = this.userService.getUserByParams(param);
            visitorApply.setApprover(user.getUserName());
            int update = this.visitorInviteService.update(visitorApply);
            if (update > 0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Map visitorInviteId = this.visitorInviteService.getVisitorInviteId(param);
                String visitorPhone = (String) visitorInviteId.get("visitorPhone");
                String visitorName = (String) visitorInviteId.get("visitorName");
                String company = (String) visitorInviteId.get("visitedCompanyPosition");
                String dateFrom = DateUtils.timeStamp2Date(Long.parseLong(visitorInviteId.get("startTime").toString())*1000+"", "yyyy-MM-dd HH:mm:ss");
                String dateEnd = DateUtils.timeStamp2Date(Long.parseLong(visitorInviteId.get("endTime").toString())*1000+"","yyyy-MM-dd HH:mm:ss");
                String projectId = (String) visitorInviteId.get("projectId");
                String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
                if (visitorPhone != null) {
                    JSONObject codeOther = new JSONObject(new LinkedHashMap<>());
                    JSONObject content = new JSONObject(new LinkedHashMap<>());
                    content.put("guestName",visitorName);
                    content.put("company",company);
                    content.put("dateFrom",dateFrom);
                    content.put("dateEnd",dateEnd);
                    content.put("VerificationCode",verifyCode);
                    String hostAddress = PropertyUtil.getProperty("server_host_address");
                    String qRCodeLink = hostAddress+"/huarun/visitor.html?projectId="+projectId+"&applyId="+applyId;
                    content.put("QRCodeLink",qRCodeLink);
                    codeOther.put("businessCode", PropertyUtil.getProperty("visitor_sms_agree_busiCode"));
                    codeOther.put("mobile", visitorPhone);
                    codeOther.put("content", content);
                    codeOther.put("secretKey", PropertyUtil.getProperty("visitor_sms_agree_secretKey"));
                    codeOther.put("source", "华润小程序");
                    codeOther.put("sourceNote", "华润小程序-审批访客预约");
                    this.log.info("========访客预约审批：开始发送短信===");
                    System.out.println("访客预约审批,短信参数: " + codeOther.toJSONString());
                    JSONObject other = HttpRequestUtils.httpPost(PropertyUtil.getProperty("visitor_sms_url"), codeOther);
                    this.log.info("========访客预约审批：发送短信完成====");
                    System.out.println("访客预约审批,短信返回: " + other);
                    if(other != null && "SUCCESS".equals(other.get("sendStatus"))){
                        Date endDate = DateUtils.parseDate(dateEnd, DateUtils.DATE_FORMAT_DATETIME);
                        long cacheTime = ((endDate.getTime() - new Date().getTime()))/1000;
                        RedisUtils redisUtils = SpringUtils.getBean(RedisUtils.class);
                        redisUtils.set("invite_visitor_"+applyId,verifyCode,cacheTime);
                    }
                }
                rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
            }
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("批准申请异常！");
            e.printStackTrace();
        }
        return rm;
    }

//    private JSONObject getOrderedJsonObject(JSONObject codeOther) {
//        LinkedHashMap<String, Object> json = JSON.parseObject(codeOther.toJSONString(),LinkedHashMap.class, Feature.OrderedField);
//        JSONObject paramJson=new JSONObject(true);
//        paramJson.putAll(json);
//        return paramJson;
//    }

    @ApiOperation(value = "拒绝", notes = "拒绝")
    @RequestMapping(value = {"/refuse"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Object> refuse(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        ResponseMessage rm = new ResponseMessage();
        try {
            VisitorApply visitorApply = new VisitorApply();
            Integer id = (Integer) map.get("id");
            String refusal = (String) map.get("refusal");
            visitorApply.setId(id);
            visitorApply.setStatus("审批已拒绝");
            visitorApply.setStatuscode(Integer.valueOf(1));
            visitorApply.setRefusal(refusal);
            visitorApply.setUpdateDate(new Date());
            String openId = req.getHeader("openId");
            Map param = new HashMap();
            param.put("openId", openId);
            User user = this.userService.getUserByParams(param);
            visitorApply.setApprover(user.getUserName());
            this.visitorInviteService.update(visitorApply);
            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("拒绝申请异常！");
            e.printStackTrace();
        }
        return rm;
    }

    @ApiOperation(value = "预约消息提示", notes = "预约消息提示")
    @RequestMapping(value = {"/getMessage"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Object> getMessage(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        ResponseMessage rm = new ResponseMessage();
        try {
            String openId = req.getHeader("openId");
            Map param = new HashMap();
            param.put("openId", openId);
            User user = this.userService.getUserByParams(param);
            String wxPhone = user.getWxPhone();
            map.put("wxPhone", wxPhone);
            Map message = this.visitorInviteService.getMessage(map);
            rm.setData(message);
            rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("拒绝申请异常！");
            e.printStackTrace();
        }
        return rm;
    }

    @ApiOperation(value = "插掉消息提示", notes = "插掉消息提示")
    @RequestMapping(value = {"/updateIsDel"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
    @ResponseBody
    public ResponseMessage<Object> updateIsDel(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        ResponseMessage rm = new ResponseMessage();
        try {
            VisitorApply entity = new VisitorApply();
            entity.setId((Integer) map.get("applyId"));
            entity.setIsDel(Integer.valueOf(1));
            int update = this.visitorInviteService.update(entity);
            if (update > 0) {
                rm.setData("成功");
                rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
            }
        } catch (Exception e) {
            rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
            this.log.error("消息异常！");
            e.printStackTrace();
        }
        return rm;
    }

    private static boolean isOverlap(String startdate1, String enddate1, String startdate2, String enddate2) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime start1,end1,start2,end2;
        try {
            start1 = LocalDateTime.parse(startdate1, df);
            end1 = LocalDateTime.parse(enddate1, df);
            start2 = LocalDateTime.parse(startdate2, df);
            end2 = LocalDateTime.parse(enddate2, df);
        } catch (Exception e) {
            return false;
        }
        DateCompareUtil.TimeSlot timeSlot1 = DateCompareUtil.buildSlot(start1, end1);
        DateCompareUtil.TimeSlot timeSlot2 = DateCompareUtil.buildSlot(start2, end2);
        return DateCompareUtil.overlapped(timeSlot1, timeSlot2);
    }

    private String getBcdApiHost(String projectId) {
        if (projectId.equals(PropertyUtil.getProperty("huarun_b_project_id")))
            return PropertyUtil.getProperty("visitor_b_url");
        if (projectId.equals(PropertyUtil.getProperty("huarun_c_project_id")))
            return PropertyUtil.getProperty("visitor_c_url");
        if (projectId.equals(PropertyUtil.getProperty("huarun_d_project_id"))) {
            return PropertyUtil.getProperty("visitor_d_url");
        }
        if (projectId.equals(PropertyUtil.getProperty("chunsun_project_id"))) {
            return PropertyUtil.getProperty("visitor_a_url");
        }
        return PropertyUtil.getProperty("visitor_bcd_url");
    }

    private String crypt(String str) {
        if ((str == null) || (str.length() == 0)) {
            throw new IllegalArgumentException("String to encript cannot be null or zero length");
        }
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] hash = md.digest();
            for (int i = 0; i < hash.length; i++)
                if ((0xFF & hash[i]) < 16)
                    hexString.append(new StringBuilder().append("0").append(Integer.toHexString(0xFF & hash[i])).toString());
                else
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return hexString.toString();
    }
}
